package com.ljc.listener;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ljc.constant.RabbitMQConstant;
import com.ljc.websocket.WebSocketService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class DanmuListener {
    /**
     * 监听发送动态普通队列
     */
    @RabbitListener(queues = RabbitMQConstant.DANMU_QUEUE_NAME)
    public void sendDanmuListener(String json, Message msg, Channel channel) throws IOException {
        JSONObject jsonObject = new Gson().fromJson(json, JSONObject.class);
        try {
            if (jsonObject == null) {
                throw new RuntimeException("sendDanmuListener参数为空");
            }
            String sessionId = jsonObject.getString("sessionId");
            String message = jsonObject.getString("message");
            // 将弹幕推送到当前连接的客户端
            WebSocketService webSocketService = WebSocketService.WEBSOCKET_MAP.get(sessionId);
            if (webSocketService.getSession().isOpen()) {
                try {
                    webSocketService.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //手动确认消息
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            log.info("动态发送成功：{}", json);
        } catch (Exception e) {
            channel.basicReject(msg.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
